//
//  CYRegeditVController.m
//  CreditAddressBook
//
//  Created by Lee on 15/4/23.
//  Copyright (c) 2015年 Lee. All rights reserved.
//  注册

#import "CYRegeditVController.h"
#import "CYLoginHttpTool.h"
#import "MBProgressHUD+MJ.h"
#import "CYEscape.h"
#import "NSObject+MJKeyValue.h"
#import "CYUser.h"
#import "MobClick.h"
#import "CYJumpsTool.h"
#import "CYABTool.h"
#import "CYLoginVController.h"
#import "CYJsonInfo.h"
#import "GCD.h"
#import "LEUUID.h"
#import "CYMeTool.h"

@interface CYRegeditVController ()<UITextFieldDelegate>

@property (weak, nonatomic) IBOutlet UIButton *loginbtn;
@property (weak, nonatomic) IBOutlet UITextField *passwordTextField;
@property (weak, nonatomic) IBOutlet UITextField *phoneTextField;
@property (weak, nonatomic) IBOutlet UITextField *smsTextField;
@property (weak, nonatomic) IBOutlet UIButton *regeditBtn;

@property(nonatomic, strong) GCDTimer *GCDTimer;

@end

@implementation CYRegeditVController

- (void)viewDidLoad {
    [super viewDidLoad];
    //设置取消按钮
    [self setupCancelBtn];
}

/**
 *  设置取消按钮
 */
- (void)setupCancelBtn {
    UIBarButtonItem *btn = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(cancelBtn)];
    btn.tintColor = CYNaviTitleColor;
    self.navigationItem.rightBarButtonItem = btn;
    
    self.regeditBtn.layer.cornerRadius = 4;
    self.regeditBtn.layer.masksToBounds = YES;
}
- (IBAction)loginclick:(id)sender {
    CYLoginVController *log = [CYLoginVController le_loadFromStoryBoard:[CYJumpsTool loginSB]];
    [self.navigationController pushViewController:log animated:YES];
    
}

- (IBAction)smsBtnClick:(id)sender {
    //检查网络
    [self countdown:sender];
    //检查电话号码是否正确
    NSString *regex = @"^(1[0-9][0-9])\\d{8}$";
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@", regex];
    BOOL isPhone = [predicate evaluateWithObject:self.phoneTextField.text];
    if (!isPhone) {
        [MBProgressHUD showError:@"请输入正确的电话号码"];
        return;
    }
    
    //确认网络有连接后发送短信验证码
    [CYLoginHttpTool sendSMSWithPhone:self.phoneTextField.text success:^(id json) {
//        CYLog(@"sms: %@", json);
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            [MBProgressHUD showSuccess:jsonInfo.message];
        }else {
            [MBProgressHUD showError:jsonInfo.message];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD showError:CYServerConnectFailure];
        CYLog(@"服务器链接失败：%@", error);
    }];
}

- (IBAction)regeditBtnClick:(id)sender {
    CYLog(@"self.phoneTextField:%@", self.phoneTextField);
    if ([self.phoneTextField.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请输入电话号码"];
    }else if ([self.smsTextField.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请输入验证码"];
    }else if ([self.passwordTextField.text isEqualToString:@""]) {
        [MBProgressHUD showError:@"请输入密码"];
    }else {
        [MBProgressHUD showMessage:@"注册中..." toView:self.view];
        //1.检查号码是否被注册
        [CYLoginHttpTool checkUserNameWithUserName:self.phoneTextField.text success:^(id json) {
            CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
            if (jsonInfo.isSuccess) {
                //2.号码没有被注册，发送注册请求
                [self reg];
            }else {
                [MBProgressHUD hideHUDForView:self.view];
                [MBProgressHUD showError:jsonInfo.message];
            }
        } failure:^(NSError *error) {
            [MBProgressHUD hideHUDForView:self.view];
            [MBProgressHUD showError:CYServerConnectFailure];
            CYLog(@"检测号码服务器连接失败：%@", error);
        }];
    }
}

- (void)reg {
    NSDictionary *par = [self params];
    //2.号码没有被注册，发送注册请求
    [CYLoginHttpTool regeditWithParams:par success:^(id json) {
        [MBProgressHUD hideHUDForView:self.view];
        CYJsonInfo *jsonInfo = [CYJsonInfo objectWithKeyValues:json];
        if (jsonInfo.isSuccess) {
            [MBProgressHUD showSuccess:jsonInfo.message];
            //统计注册用户
            [MobClick event:@"regedit"];
            [CYMeTool backgroundCloudSyn];
            //注册成功登陆
            [CYLoginVController loginWithPhone:par[@"phone"] password:self.passwordTextField.text view:self.view complete:^{
                //登陆成功跳转到首页
                [self cancelBtn];
            }];
        }else {
            [MBProgressHUD showError:jsonInfo.message];
        }
    } failure:^(NSError *error) {
        [MBProgressHUD hideHUDForView:self.view];
        [MBProgressHUD showError:CYServerConnectFailure];
        CYLog(@"注册失败%@", error);
    }];
}

- (CYUser *)setupUser {
    CYUser *user = [[CYUser alloc] init];
    user.phone = self.phoneTextField.text;
    user.headPic = @"";
    user.userId = @"";
    user.nickName = @"";
    return user;
}
//新接口type=2
- (NSDictionary *)params {
    NSString *str = [LEUUID UUIDForVendor];
    NSDictionary *params = @{@"userPassword": [CYEscape encrypt:self.passwordTextField.text], @"phone": self.phoneTextField.text, @"type": @"2", @"userName": self.phoneTextField.text, @"phoneCode": self.smsTextField.text,@"machineCode":str};
    return params;
}

/**
 *  倒计时
 */
- (void)countdown:(UIButton *)btn {
    self.GCDTimer = [[GCDTimer alloc] initInQueue:[GCDQueue mainQueue]];
    
    CYWeakObject(weakself, self);
    __block int time = 59;
    [self.GCDTimer event:^{
        if (time < 1) {
            //设置界面的按钮显示 根据自己需求设置
            [btn setTitle:@"发送验证码" forState:UIControlStateNormal];
            btn.userInteractionEnabled = YES;
            btn.backgroundColor = CYColor(79, 118, 245, 1);
            [weakself.GCDTimer destroy];
        } else {
            //        NSLog(@"time:%d", time);
            [btn setTitle:[NSString stringWithFormat:@"%ds",time] forState:UIControlStateNormal];
            btn.userInteractionEnabled = NO;
            btn.backgroundColor = [UIColor grayColor];
        }
        time--;
    } timeInterval:NSEC_PER_SEC * 1];
    [self.GCDTimer start];
}

/**
 *  取消按钮方法
 */
- (void)cancelBtn {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)dealloc {
    CYLog(@"注册销毁");
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

/**
 *  屏幕点击时触发
 */
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
//    CYLog(@"点击屏幕");
    [self.view.window endEditing:YES];
}

@end
